package my.netty.bootstrap;

import my.netty.channel.ClientChannel;
import my.netty.channel.EventLoopGroup;
import my.netty.channel.handler.ChannelInitializer;
import my.netty.exception.ChannelException;

import java.net.InetSocketAddress;

public class Bootstrap {

    private EventLoopGroup workerGroup;

    private Class<? extends ClientChannel> channelClass;
    private ClientChannel channel;
    private ChannelInitializer initializer;

    public Bootstrap group(EventLoopGroup workerGroup) {
        this.workerGroup = workerGroup;
        return this;
    }

    public Bootstrap channel(Class<? extends ClientChannel> channelClass) {
        this.channelClass = channelClass;
        return this;
    }

    public Bootstrap handler(ChannelInitializer channelInitializer) {
        this.initializer = channelInitializer;
        return this;
    }

    public ClientChannel connect(String host, int port) {
        try {
            this.channel = channelClass.newInstance();
            initializer.initChannel(this.channel);
        } catch (Throwable e) {
            if (this.channel != null) {
                this.channel.close();
            }
            throw new ChannelException("init channel", e);
        }
        workerGroup.register(this.channel);
        this.channel.connect(new InetSocketAddress(host, port));
        return channel;
    }
}
